from os import linesep

import pypm

from zope.interface import implements

from twisted.plugin import IPlugin

from toneedu.interfaces import ISoundDevice
from toneedu.exceptions import NotInitedDevice, NoSuchSoundDevice

class Midi(object):
    implements(IPlugin, ISoundDevice)

    def __init__(self):
        pypm.Initialize()
        self.midiOut = None
        self.outDevs = {}
        self._enumerateDevices()

    def getOutputDevices(self):
        return self.outDevs

    def initDevice(self, devnum):
        if devnum not in self.outDevs:
            raise NoSuchSoundDevice(devnum)
        if self.midiOut is not None:
            self.terminate()
            pypm.Initialize()
        self.midiOut = pypm.Output(devnum, 1)
        self.midiOut.WriteShort(0xc0, 0, 0)

    def terminate(self):
        self.midiOut = None
        pypm.Terminate()

        
    def playChord(self, chord, delay = 200):
        if not self.isInited():
            raise NotInitedDevice
        chordList = []
        midiTime = pypm.Time() + 10
        for loop in range(len(chord)):
            chordList.append([[0x90, chord[loop], 100], midiTime + delay * loop])
            chordList.append([[0x80, chord[loop], 0], midiTime + 2000 + delay * loop])
        self.midiOut.Write(chordList)

    def isInited(self):
        return self.midiOut is not None
    
    def _enumerateDevices(self):
        self.outDevs = {}

        for loop in range(pypm.CountDevices()):
            interf, name, input, output, opened = pypm.GetDeviceInfo(loop)
            if output == 1:
                self.outDevs[loop] = name

midi = Midi()
